import re

from django_redis import get_redis_connection
from rest_framework import serializers

from .models import User

# 创建序列化器

class RegisterCreateSerializer(serializers.ModelSerializer):

    """
    定义三个字段

    校验密码，
    短信验证码，
    是否同意协议

    """
    password2 = serializers.CharField(label='校验密码',allow_null=False,allow_blank=False,write_only=True)
    sms_code = serializers.CharField(label='短信验证码',max_length=6,min_length=6,allow_null=False,allow_blank=False,write_only=True)
    allow = serializers.CharField(label='是否同意协议',allow_null=False,allow_blank=False,write_only=True)


    class Meta:
        model = User
        fields = ('id','username','password','mobile','password2','sms_code','allow')

        extra_kwargs = {
            'id':{'read_only':True},
            'username':{
                'min_length':5,
                'max_length':20,
                'error_messages':{
                    'min_length':'仅允许５－２０个字符的用户名',
                    'max_length':'仅允许５－２０个字符的用户名',
                }
            },
            'password':{
                'write_only':True,
                'min_length':8,
                'max_length':20,
                'error_messages':{
                    'min_length':'仅允许８－２０个字符的密码',
                    'max_length':'仅允许８－２０个字符的密码',
                }
            }
        }

    # 单个字段校验

    def validate_mobile(self,value):
        if not re.match(r'1[345789]\d{9}',value):
            raise serializers.ValidationError('手机号格式不正确')

        return value

    def validate_allow(self, value):
        if value != 'true':
            raise serializers.ValidationError('您未同意协议')
        return value

    # 多字段校验 密码是否一致　短信验证码是否一致
    def validate(self, attrs):
        password = attrs.get('password')
        password2 = attrs.get('password2')

        if password != password2:
            raise serializers.ValidationError('密码不一致')

        #　比较手机验证码
        # 获取用户提交的验证码
        code = attrs.get('sms_code')
        redis_conn = get_redis_connection('code')
        # 获取手机号码
        mobile = attrs.get('mobile')
        redis_code = redis_conn.get('sms_'+mobile)
        if redis_code is None:
            raise serializers.ValidationError('验证码已过期')

        if redis_code.decode() != code:
            raise serializers.ValidationError('验证码不正确')

        return attrs

    def create(self, validated_data):

        # 删除多余字段
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        user = super().create(validated_data)


        user.set_password(validated_data['password'])
        user.save()

        return user